package code.module.chat
{
	import code.main.modle.lang.Language;
	
	import com.yy.tools.menu.Menu;
	import com.yy.tools.string.StringUtil;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.ContextMenuEvent;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.ContextMenuItem;

	/**
	 *聊天控制器 
	 * @author YY
	 * 
	 */
	public class TableChat
	{
		public static const SEND_CHAT_MSG:int = 1;
		
		private var _chatPanel:ChatPanel;
		private var _cb:Function;
		private var _msgArr:Array;
		private var _parent:DisplayObjectContainer;
		public function TableChat(parent:DisplayObjectContainer, cb:Function)
		{
			_parent = parent;
			_cb = cb;
			_chatPanel = new ChatPanel();
			init();
		}
		
		private function init():void {
			reset();
			_chatPanel.sendChatBtn.addEventListener(MouseEvent.CLICK, sendFunc);
			_chatPanel.chatInput.addEventListener(KeyboardEvent.KEY_DOWN, keyDownFunc);
			
			var verMenu:Menu = new Menu(_chatPanel);
			var item:ContextMenuItem = new ContextMenuItem(Language.TABLE_CHAT[0]);
			item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, clear);
			verMenu.addMenuItem(item);
		}
		
		private function clear(obj:Object=null):void {
			_chatPanel.clear();
			_msgArr = [];
		}
		private function sendFunc(e:Event):void {
			var str:String = _chatPanel.chatInput.text;
			str = StringUtil.trim(str);
			if(str != "") {
				_cb(SEND_CHAT_MSG, {msg:str});
			}
			_chatPanel.chatInput.text = "";
		}
		private function keyDownFunc(e:KeyboardEvent):void{
			var key:int = e.keyCode;
			trace(key);
			if(key == 13) {
				sendFunc(null);
			}
		}
		
		public function show():void {
			if(_parent) {
				_parent.addChild(_chatPanel);
				_chatPanel.x = 0;
				_chatPanel.y = 584;
			}
		}
		public function hide():void {
			if(_parent && _parent.contains(_chatPanel)) {
				_parent.removeChild(_chatPanel);
			}
		}
		
		/**
		 *重置聊天 
		 * 
		 */
		public function reset():void {
			_msgArr = [];
		}
		
		/**
		 *显示消息 
		 * @param uName
		 * @param msg
		 * 
		 */
		public function showMsg(uName:String, msg:String):void {
			if(uName) {
				addContent(uName + "：" +  msg);
			}
			_chatPanel.showText(getMsg());
		}
		
		/**
		 *添加内容 
		 * @param msg
		 * 
		 */
		private function addContent(msg:String):void {
			_msgArr.push(msg);
			if(_msgArr.length>50) {
				_msgArr.shift();
			}
		}
		
		/**
		 *生成消息 
		 * @return 
		 * 
		 */
		private function getMsg():String {
			var str:String = "";
			var i:int;
			var len:int = _msgArr.length;
			for(i=0; i<len; i++) {
				str += _msgArr[i] + "\n";
			}
			return str;
		}
	}
}